﻿using LeSoft.Application.Bussiness;
using LeSoft.Application.Code;
using LeSoft.Application.Entity;
using LeSoft.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LeSoft.Application.Web.Controllers
{
    public class PersonCenterController : MvcControllerBase
    {

        private AccountBLL accountBLL = new AccountBLL();
        private static Byte[] bt;
        #region 视图功能
        /// <summary>
        /// 个人中心
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Index()
        {
            ViewBag.userId = OperatorProvider.Provider.Current().UserId;
            return View();
        }


        #endregion

        #region 获取数据
        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult VerifyCode()
        {
            return File(new VerifyCode().GetVerifyCode(), @"image/Gif");
        }


        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="keyValue">用户ID</param>
        /// <returns>用户信息</returns>
        [HttpGet]
        public ActionResult GetUserInfo(string keyValue)
        {
            var data = accountBLL.GetEntity(keyValue);
            if (data.HeadIcon != null) GenerateImage(data.HeadIcon, data.Id);


            string type = "";
            switch (data.AccountType.ToString())
            {
                case "1": type = "超级管理员";
                    break;
                case "2": type = "员工";
                    break;
                case "3": type = "客户";
                    break;
                default: type = "其他";
                    break;
            }
            var query = new WorkerBLL().GetEntity(keyValue);
            if (data.AccountType.ToString() == "2" && !query.IsEmpty())
            {

                try
                {
                    string CompanyName = (new OrganizeBLL().GetEntity(query.OrganizeId)).IsEmpty() ? "" : new OrganizeBLL().GetEntity(query.OrganizeId).FullName;
                    string DepartmentName = (new DepartmentBLL().GetEntity(query.DepartmentId)).IsEmpty() ? "" : new DepartmentBLL().GetEntity(query.DepartmentId).FullName;
                    string ManagerName = (new WorkerBLL().GetEntity(query.PstructId)).IsEmpty() ? "" : new WorkerBLL().GetEntity(query.PstructId).Name;
                    string DutyName = (new DutyBLL().GetEntity(query.DutyId)).IsEmpty() ? "" : new DutyBLL().GetEntity(query.DutyId).FullName;
                    string PostName = (new PostBLL().GetEntity(query.PostId)).IsEmpty() ? "" : new PostBLL().GetEntity(query.PostId).FullName;
                    string RoleName = (new RoleBLL().GetEntity(query.RoleId)).IsEmpty() ? "" : new RoleBLL().GetEntity(query.RoleId).FullName;


                    var UserBaseInfo = new
                    {
                        Id = data.Id,
                        Account = data.Account,
                        AccountType = type,
                        EnCode = data.Code,
                        Name = data.Name,
                        Gender = query.Gender,
                        CompanyName = CompanyName,
                        DepartmentName = DepartmentName,
                        ManagerName = ManagerName,
                        DutyName = DutyName,
                        PostName = PostName,
                        RoleName = RoleName,
                        Mobile = query.PhoneNum,
                        Telephone = query.TelPhoneNum,
                        Email = query.Email,
                        HeadIcon = data.HeadIcon,
                        Description = query.Description
                    };
                    return Content(UserBaseInfo.ToJson());
                }
                catch (Exception e)
                {

                    throw;
                }

            }
            else
            {

                var UserBaseInfo = new
                {
                    Id = data.Id,
                    Account = data.Account,
                    AccountType = type,
                    EnCode = data.Code,
                    Name = data.Name,
                    HeadIcon = data.HeadIcon,
                };
                return Content(UserBaseInfo.ToJson());
            }

        }

        /// <summary>
        /// 读取头像
        /// </summary>
        /// <param name="bt"></param>
        /// <param name="name"></param>
        public void GenerateImage(Byte[] bt, string name)
        {
            int ArraySize = bt.GetUpperBound(0);//获得数据库中存储的位流数组的维度上限，用作读取流的上限    

            string virtualPath = HttpRuntime.AppDomainAppPath + string.Format("/Resource/PhotoFile/{0}.jpg", name);
            DirectoryInfo dd = new DirectoryInfo(HttpRuntime.AppDomainAppPath + "/Resource/PhotoFile");
            if (dd.Exists)
            {
                FileStream fs = new FileStream(virtualPath, FileMode.OpenOrCreate, FileAccess.Write);
                fs.Write(bt, 0, ArraySize);
                fs.Close();   //-- 写入到virtualPath。
            }
            else
            {
                dd.Create();
                FileStream fs = new FileStream(virtualPath, FileMode.OpenOrCreate, FileAccess.Write);
                fs.Write(bt, 0, ArraySize);
                fs.Close();   //-- 写入到virtualPath。
            }

        }
        /// <summary>
        /// 保存头像
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        public ActionResult SaveHeadIcon(string keyValue)
        {
            var entity = accountBLL.GetEntity(keyValue);
            entity.HeadIcon = bt;
            try
            {
                accountBLL.SaveForm(keyValue, entity);
                return Success("保存成功！");
            }
            catch (Exception e)
            {
                return Error(e.Message);
            }


        }

        //保存联系方式
        public ActionResult SaveContact(string keyValue, WorkerEntity entity)
        {
            var data = new WorkerBLL().GetEntity(keyValue);
            data.PhoneNum = entity.PhoneNum;
            data.TelPhoneNum = entity.TelPhoneNum;
            data.Email = entity.Email;
            try
            {
                new WorkerBLL().SaveForm(data.Id, data);
                return Success("操作成功！");
            }
            catch (Exception e)
            {

                return Error(e.Message);
            }
        }

        public ActionResult UploadFile1()
        {
            HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
            //没有文件上传，直接返回
            if (files[0].ContentLength == 0 || string.IsNullOrEmpty(files[0].FileName))
            {
                return HttpNotFound();
            }
            var fs = files[0].InputStream;
            bt = new byte[fs.Length];
            fs.Read(bt, 0, Convert.ToInt32(fs.Length));
            fs.Close();
            return Success("上传成功。");
        }
        #endregion

        #region 提交数据
        /// <summary>
        /// 上传头像
        /// </summary>
        /// <returns></returns>
        public ActionResult UploadFile()
        {

            HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
            //没有文件上传，直接返回
            if (files[0].ContentLength == 0 || string.IsNullOrEmpty(files[0].FileName))
            {
                return HttpNotFound();
            }
            //string FileEextension = Path.GetExtension(files[0].FileName);
            string UserId = OperatorProvider.Provider.Current().UserId;
            //string virtualPath = string.Format("/Resource/PhotoFile/{0}{1}", UserId, FileEextension);
            //string fullFileName = Server.MapPath("~" + virtualPath);
            ////创建文件夹，保存文件
            //string path = Path.GetDirectoryName(fullFileName);
            //Directory.CreateDirectory(path);
            //files[0].SaveAs(fullFileName);
            AccountEntity userEntity = new AccountBLL().GetEntity(UserId);
            var fs = files[0].InputStream;
            userEntity.HeadIcon = new byte[fs.Length];
            new AccountBLL().SaveForm(userEntity.Id, userEntity);
            return Success("上传成功。");
        }
        /// <summary>
        /// 验证旧密码
        /// </summary>
        /// <param name="OldPassword"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ValidationOldPassword(string OldPassword)
        {
            OldPassword = Md5Helper.MD5(DESEncrypt.Encrypt(Md5Helper.MD5(OldPassword, 32).ToLower(), OperatorProvider.Provider.Current().SecretKey).ToLower(), 32).ToLower();
            if (OldPassword != OperatorProvider.Provider.Current().Password)
            {

                return Error("原密码错误，请重新输入");
            }
            else
            {
                return Success("通过信息验证");
            }
        }
        /// <summary>
        /// 提交修改密码
        /// </summary>
        /// <param name="userId">当前用户Id</param>
        /// <param name="password">新密码</param>
        /// <param name="oldPassword">旧密码</param>
        /// <param name="verifyCode">验证码</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SubmitResetPassword(string password, string oldPassword, string verifyCode)
        {
            verifyCode = Md5Helper.MD5(verifyCode.ToLower(), 16);
            if (Session["session_verifycode"].IsEmpty() || verifyCode != Session["session_verifycode"].ToString())
            {
                return Error("验证码错误，请重新输入");
            }
            oldPassword = Md5Helper.MD5(DESEncrypt.Encrypt(oldPassword, OperatorProvider.Provider.Current().SecretKey).ToLower(), 32).ToLower();
            if (oldPassword != OperatorProvider.Provider.Current().Password)
            {
                return Error("原密码错误，请重新输入");
            }

            new AccountBLL().RevisePassword(OperatorProvider.Provider.Current().UserId, password.ToLower());
            Session.Abandon(); Session.Clear();
            return Success("密码修改成功，请牢记新密码。\r 将会自动安全退出。");
        }
        #endregion


        public ActionResult GetWXImg()
        {
            try
            { 
                var data = new { type = 1, Url = new WorkerBLL().GetWXImg() };
                return Content(data.ToJson());
            }
            catch (Exception e)
            {
                return Error(e.Message);
                throw;
            }


        }
    }
}
